package cn.gcjxsc.payment.service.wx;

import cn.gcjxsc.common.consts.PayStatus;
import cn.gcjxsc.payment.data.WeChatConfig;
import cn.gcjxsc.payment.data.pay.PayData;
import cn.gcjxsc.payment.entity.wx.PayRecord;
import cn.gcjxsc.payment.repository.wx.PayRecordRepository;
import com.zgxl.common.util.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @author pumbaa
 * @since 1.0
 */
@Service("wxPayRecordService")
public class PayRecordService {

    @Autowired
    private PayRecordRepository payRecordRepository;

    @Transactional
    public PayRecord saveOrUpdate(PayRecord record) {
        return payRecordRepository.save(record);
    }

    /**
     * 根据系统流水号查询支付记录
     *
     * @param tradeNo 系统交易
     * @return 返回支付记录
     */
    public PayRecord findByTradeNo(String tradeNo) {
        return payRecordRepository.findByTradeNo(tradeNo);
    }

    /**
     * 根据系统流水号查询支付记录
     *
     * @param sn 系统交易
     * @return 返回支付记录
     */
    public PayRecord findBySn(String sn) {
        return payRecordRepository.findBySn(sn);
    }

    /**
     * 根据微信交易号查询支付记录
     *
     * @param tradeNo 微信交易号
     * @return 返回支付记录
     */
    public PayRecord findByOutTradeNo(String tradeNo) {
        return payRecordRepository.findByOutTradeNo(tradeNo);
    }

    public PayRecord newPayRecord(PayData payData, WeChatConfig config) {
        PayRecord record = new PayRecord();
        record.setMerId(config.getMch_id());
        record.setAttach(payData.getAttach());
        record.setAppId(config.getAppid());
        record.setAmount(payData.getAmount());
        record.setTradeTime(0L);
        record.setStatus(PayStatus.UNPAY.ordinal());
        record.setOpenid(payData.getOpenid());
        record.setOutTradeNo("");
        record.setSn(payData.getSn());
        record.setTradeNo(createTradeNo(7));
        record.setCreated(DateTimeUtil.getTimestamp());
        record.setNotifyUrl(payData.getNotify());
        record.setSnDiscr(payData.getSnDiscr());
        return record;
    }

    public String createTradeNo(int len) {
        String sn = DateTimeUtil.generateSn();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            sb.append((int) (Math.random() * 10));
        }
        return "7" + sn + sb.toString();
    }

}
